(() => {
    const emit = (event, data) => {
        if (frappe.realtime?.trigger) {
            frappe.realtime.trigger(event, data);
        } else {
            document.dispatchEvent(new CustomEvent(event, { detail: data }));
        }
    };

    // 路由变化
    frappe.router?.on('change', () => emit('global_loading', true));

    // AJAX拦截
    const _originalAjax = frappe.ajax;
    frappe.ajax = function(opts) {
        if (!opts.background) emit('global_loading', true);
        return _originalAjax.call(this, opts)
            .always(() => !opts.background && emit('global_loading', false));
    };

    // 表单加载
    frappe.ui.form?.on('FormLoad', () => emit('global_loading', false));
})();